/**
 * Created by doucharles1 on 16/3/21.
 */
var _=require("underscore")
var async=require("async")
var util=require("util")
var ObjectID=require("mongodb").ObjectID

objBadgeColl=$objMongoColls["maindb"]["badge"]
objUserBadgeColl=$objMongoColls["maindb"]["user_badge"]

/*
 badge:{
    _id:<ObjectID>,
    img_logo:""
    subject:"活动徽章",
    origin:"",
    dt_create:<Datetime>,
    binding:{
        "collection":<string>,
        "_id":<ObjectID>
    },
    _id_publish_user:<ObjectID>
 }

 user_badge:{
    _id:<ObjectID>,
    _id_badge:<ObjectID>,
    _id_user:<ObjectID>,
    dt_achieve:<Datetime>
 }
 */

$dao["badge"]["insertOneBadge"]=function(userid,objBadgeInfo,funcCb){
    objBadgeInfo["_id_publish_user"]=userid
    objBadgeInfo["dt_create"]=new Date()

    objBadgeColl.insertOne(objBadgeInfo,function(err,objResult){
        if(err){
            req.junkfiles=objBadgeInfo["img_logo"]
            funcCb(1000,null)
        }else{
            funcCb(0,objResult["insertedId"].toHexString())
        }
    })
}

$dao["badge"]["updateBadgeInfo"]= function (objBadgeID,objBadgeInfo,funcCb){
    objBadgeColl.findOneAndUpdate({_id:objBadgeID},{$set:objBadgeInfo},{projection:{_id:0,img_logo:1}},function(err,objResult){
        if(err){
            req.junkfiles=[objBadgeInfo["img_logo"]]
            funcCb(1002)
        }else{
            req.junkfiles=[objResult["img_logo"]]
            funcCb(0)
        }
    })
}

$dao["badge"]["queryOneByID"]=function(strBagdeID,funcCb){
    var objBadgeID=new ObjectID(strBagdeID)

    objBadgeColl.findOne({_id:objBadgeID},function(err,objResult){
        if(err){
            funcCb(1001,null)
        }else{
            funcCb(0,objResult)
        }
    })
}

$dao["badge"]["grant"]=function(userid,badgeid,funcCb){
    var objInserted={
        _id_user:userid,
        _id_badge:badgeid,
        dt_achieve:new Date()
    }
    objUserBadgeColl.insertOne(objInserted,function(err,cResult){
        if(err){
            funcCb({errcode:1000},null)
        }else{
            funcCb(null,null)
        }
    })
}